package top.codetheory.thread._001_打断;

import lombok.extern.slf4j.Slf4j;

/**
 * @author:
 * @since: 2024/5/8 上午11:45
 **/
@Slf4j
public class _008_二阶段终止模式_使用停止标记 {
    public static void main(String[] args) {
        TPTVolatile tptVolatile = new TPTVolatile();
        tptVolatile.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        tptVolatile.stop();
    }
}
@Slf4j
class TPTVolatile {
    private Thread thread;
    private volatile boolean stop = false;

    public void start() {
        thread = new Thread(() -> {
            while (true) {
                if (stop) {
                    log.info("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);  // 防止cpu空转
                    log.info("执行业务");
                } catch (InterruptedException e) {
                    log.info("被打断了");
                }

            }
        }, "t1");
        thread.start();
    }

    public void stop() {
        stop = true;
        thread.interrupt();  // 让线程能立即停止
    }
}